package com.jyw.business.obstacles.utils;

import com.jyw.business.obstacles.websocket.config.WsSessionManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.util.Collection;

/**
 * @author 沈峻
 * @ClassName WebScoketUtils
 * @Description TODO
 * @Date 2023/8/22 16:11
 **/
@Slf4j
public class WebSocketUtils {
    /**
     * 长连接发送消息
     * @param msg
     * @param userId
     */
    public static void send(String msg,Long userId){
        WebSocketSession webSocketSession = WsSessionManager.get(userId);
        try {
            webSocketSession.sendMessage(new TextMessage(msg));
        } catch (IOException e) {
            log.error("发送消息失败",e);
        }
    }

    /**
     * 给所有连接的用户发送广播
     * @param msg
     */
    public static void broad(String msg){
        Collection<WebSocketSession> sessionCollection = WsSessionManager.getAll();
        sessionCollection.forEach(session->{
            try {
                session.sendMessage(new TextMessage(msg));
            } catch (IOException e) {
                log.error("发送消息失败",e);
            }
        });
    }
}
